package com.ruoyi.cems.service.impl;

import java.util.*;

import com.ruoyi.cems.domain.*;
import com.ruoyi.cems.domain.dto.BmsWorkChecklistDTO;
import com.ruoyi.cems.domain.dto.TaskProgressDTO;
import com.ruoyi.cems.service.IBmsEmergencyNoticeService;
import com.ruoyi.cems.service.IBmsUserMessageService;
import com.ruoyi.cems.service.IBmsWorkChecklistsDetailService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.cems.mapper.BmsWorkChecklistsMapper;
import com.ruoyi.cems.service.IBmsWorkChecklistsService;

/**
 * 工作检查单Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-07-23
 */
@Service
public class BmsWorkChecklistsServiceImpl implements IBmsWorkChecklistsService
{
    @Autowired
    private BmsWorkChecklistsMapper bmsWorkChecklistsMapper;

    @Autowired
    private IBmsEmergencyNoticeService emergencyNoticeService;

    @Autowired
    private IBmsWorkChecklistsDetailService checklistsDetailService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IBmsUserMessageService bmsUserMessageService;
    /**
     * 查询工作检查单
     * 
     * @param ID 工作检查单主键
     * @return 工作检查单
     */
    @Override
    public BmsWorkChecklists selectBmsWorkChecklistsByID(String ID)
    {
        return bmsWorkChecklistsMapper.selectBmsWorkChecklistsByID(ID);
    }

    /**
     * 查询工作检查单列表
     * 
     * @param bmsWorkChecklists 工作检查单
     * @return 工作检查单
     */
    @Override
    public List<BmsWorkChecklists> selectBmsWorkChecklistsList(BmsWorkChecklists bmsWorkChecklists)
    {
        return bmsWorkChecklistsMapper.selectBmsWorkChecklistsList(bmsWorkChecklists);
    }
    @Override
    public List<BmsWorkChecklists> selectBmsWorkChecklistsByEnID(String enId)
    {
        return bmsWorkChecklistsMapper.selectBmsWorkChecklistsByEnID(enId);
    }

    @Override
    public List<BmsWorkChecklists> selectBmsWorkChecklistsListById(String id) {
        return null;
    }

    /**
     * 新增工作检查单
     * 
     * @param bmsWorkChecklists 工作检查单
     * @return 结果
     */
    @Override
    public int insertBmsWorkChecklists(BmsWorkChecklists bmsWorkChecklists)
    {
        return bmsWorkChecklistsMapper.insertBmsWorkChecklists(bmsWorkChecklists);
    }

    @Override
    public int updateBmsWorkChecklistsByEnId(String enId){
        return bmsWorkChecklistsMapper.updateBmsWorkChecklistsByEnId(enId);
    }

    /**
     * 修改工作检查单
     * 
     * @param bmsWorkChecklists 工作检查单
     * @return 结果
     */
    @Override
    public int updateBmsWorkChecklists(BmsWorkChecklists bmsWorkChecklists)
    {
        return bmsWorkChecklistsMapper.updateBmsWorkChecklists(bmsWorkChecklists);
    }

    /**
     * 批量删除工作检查单
     * 
     * @param IDs 需要删除的工作检查单主键
     * @return 结果
     */
    @Override
    public int deleteBmsWorkChecklistsByIDs(String[] IDs)
    {
        return bmsWorkChecklistsMapper.deleteBmsWorkChecklistsByIDs(IDs);
    }

    /**
     * 删除工作检查单信息
     * 
     * @param ID 工作检查单主键
     * @return 结果
     */
    @Override
    public int deleteBmsWorkChecklistsByID(String ID)
    {
        return bmsWorkChecklistsMapper.deleteBmsWorkChecklistsByID(ID);
    }

    @Override
    public Map<String, Object> getFilledWorkChecklistsById(String id) {
        Map<String, Object>resultMap = new HashMap<>();
        //获取检查单
        BmsWorkChecklists bmsWorkChecklists = bmsWorkChecklistsMapper.selectBmsWorkChecklistsByID(id);
        resultMap.put("checkList", bmsWorkChecklists);
        if(bmsWorkChecklists != null){
            //获取应急通知单
            BmsEmergencyNotice bmsEmergencyNotice = emergencyNoticeService.selectBmsEmergencyNoticeByID(bmsWorkChecklists.getEnId());
            resultMap.put("notice", bmsEmergencyNotice);
            //获取检查项列表
            BmsWorkChecklistsDetail detail = new BmsWorkChecklistsDetail();
            detail.setCheckId(id);
            List<BmsWorkChecklistsDetail> bmsWorkChecklistsDetails = checklistsDetailService.selectBmsWorkChecklistsDetailList(detail);
            resultMap.put("checkListDetail", bmsWorkChecklistsDetails);
        }
        return resultMap;
    }

    @Override
    public String fillWorkCheckDetail(BmsWorkChecklistDTO dto) {
        //更新检查单项填报结果
        dto.getChecklistsDetails().forEach(detail -> {
            detail.setFillPeople(dto.getFillPeople());
            detail.setFileTime(new Date());
            detail.setUpdatedBy(dto.getFillPeople());
            detail.setUpdatedTime(new Date());
            checklistsDetailService.updateBmsWorkChecklistsDetail(detail);
        });

        boolean flag = false;
        BmsWorkChecklistsDetail bwcld = new BmsWorkChecklistsDetail();
        bwcld.setCheckId(dto.getId());
        List<BmsWorkChecklistsDetail> checklistsDetails = checklistsDetailService.selectBmsWorkChecklistsDetailList(bwcld);
        if (checklistsDetails != null) {
            // 使用 anyMatch 方法检查是否存在 fillPeople 不为 null 的 detail
            flag = checklistsDetails.stream().anyMatch(detail -> detail.getFillPeople() != null);
        }
        if (flag){
            BmsWorkChecklists bmsWorkChecklists = new BmsWorkChecklists();
            bmsWorkChecklists.setID(dto.getId());
            bmsWorkChecklists.setStatus("已提交");
            bmsWorkChecklistsMapper.updateBmsWorkChecklists(bmsWorkChecklists);
        }
        return "填报成功";
    }

    @Override
    public int reportToDuty(String ID) {
        return bmsWorkChecklistsMapper.reportToDuty(ID);
    }

    /**
     * 转移检查单及详情
     *
     * @param noticeId    通知id
     * @param checkListId 检查单id
     * @param userId      接收用户ID
     */
    @Override
    public String transfer(String noticeId, String checkListId, Long userId) {
        // 参数非空检查
        if (StringUtils.isNotEmpty(noticeId) && StringUtils.isNotEmpty(checkListId) && userId != null) {
            // 获取检查单信息
            BmsWorkChecklists bmsWorkChecklists = bmsWorkChecklistsMapper.selectBmsWorkChecklistsByID(checkListId);
            if (bmsWorkChecklists == null) {
                throw new UtilException("检查单不存在");
            }

            // 获取用户信息
            SysUser sysUser = sysUserService.selectUserById(userId);
            if (sysUser == null) {
                throw new UtilException("用户不存在");
            }

            // 更新检查单信息
            bmsWorkChecklists.setJobNumber(sysUser.getJobNumber());
            bmsWorkChecklists.setCheckPeople(sysUser.getName());
            bmsWorkChecklists.setCheckPeopleId(userId.toString());
            bmsWorkChecklists.setPhone(sysUser.getPhonenumber());

            // 更新数据库
            int updateResult = bmsWorkChecklistsMapper.updateBmsWorkChecklists(bmsWorkChecklists);
            if (updateResult <= 0) {
                throw new UtilException("更新检查单失败");
            }

            // 发送消息
            userMessage(bmsWorkChecklists, userId.toString());

            return "转移成功";
        } else {
            throw new IllegalArgumentException("参数不能为空");
        }
    }

    /**
     * 获取任务进度
     *
     * @param taskNo
     * @return
     */
    @Override
    public List<TaskProgressDTO> getTaskProgress(String taskNo,String groupName) {
        return bmsWorkChecklistsMapper.getTaskProgress(taskNo,groupName);
    }

    private void userMessage(BmsWorkChecklists bmsWorkChecklists,String userId){
        //生成系统消息
        BmsUserMessage bmsUserMessage = new BmsUserMessage();
        bmsUserMessage.setID(UUID.randomUUID().toString().replace("-", ""));
        bmsUserMessage.setCreatedBy(userId);
        bmsUserMessage.setCreatedTime(new Date());
        bmsUserMessage.setUserId(userId);
        bmsUserMessage.setType(3);
        bmsUserMessage.setMessage("用户["+bmsWorkChecklists.getCheckPeople()+"]将试飞任务单号为【"+bmsWorkChecklists.getTaskNo()+"】的检查单转移给您，请及时处理！");
        bmsUserMessageService.insertBmsUserMessage(bmsUserMessage);
    }
}
